package com.szewec.ps.util;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;

import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.szewec.ps.R;
import com.szewec.ps.base.Constants;
import com.szewec.ps.greenDao.api.BaseManagerFactory;
import com.szewec.ps.greenDao.dao.AlbumFile;
import com.szewec.ps.myview.recordsound.RecordSoundDialog;
import com.szewec.ps.util.imagepicker.ImagePickerProvider;
import com.szewec.ps.util.imagepicker.data.MediaFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * create by zzy
 * 2019.9.23
 */
public class PhotoVideoUtil {
    private static String TAG = "PhotoVideoUtil";

    /**
     * 调用系统相机拍照
     *
     * @param activity
     * @param requestCode 请求码
     * @return 返回保存路径
     */
    public static String showCamera(Activity activity, int requestCode) {

        //拍照存放路径
        File fileDir = new File(Environment.getExternalStorageDirectory(), "Photo");
        if (!fileDir.exists()) {
            fileDir.mkdir();
        }
        String mFilePath = fileDir.getAbsolutePath() + "/IMG_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".jpg";

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(activity, ImagePickerProvider.getFileProviderName(activity), new File(mFilePath));
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        } else {
            uri = Uri.fromFile(new File(mFilePath));
        }


        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, 10 * 1024 * 1024L);//限制图片大小(10M=10 * 1024 * 1024L)
        activity.startActivityForResult(intent, requestCode);

        return mFilePath;
    }

    /**
     * 调用系统录音机
     */
    public static String createRecordSoundFilePath() {
        //录音存放路径
        File fileDir = new File(Environment.getExternalStorageDirectory(), "recordSounds");
        if (!fileDir.exists()) {
            fileDir.mkdir();
        }
        String mFilePath = fileDir.getAbsolutePath() + "/AMR_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".amr";
        new File(mFilePath);

        return mFilePath;
    }



    /**
     * 存储录音
     */
    public static void saveRecordSound(Activity activity, String filePath,RecordSoundDialog.StopedClickedListener listener){
        new RecordSoundDialog(activity, R.style.transparentFrameWindowStyle, 1,filePath, listener).show();
    }

    public static void playRecordSound(Activity activity, String filePath){
        new RecordSoundDialog(activity, R.style.transparentFrameWindowStyle, 2,filePath, null).show();
    }


    /**
     * 调用系统相机录制
     *
     * @param activity
     * @param requestCodeVideo 请求码
     * @return 返回保存路径
     */
    public static String takeVideo(Activity activity, int requestCodeVideo) {
        Intent intentVIDEO = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        Uri fileUri = null;
        //视频存放路径
        File fileDir = new File(Environment.getExternalStorageDirectory(), "Video");
        if (!fileDir.exists()) {
            fileDir.mkdir();
        }
        String mFilePath = fileDir.getAbsolutePath() + "/VID_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".mp4";

        //安卓Build.VERSION_CODES.M以上必须做处理
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //做一些处理
            //获取uri
            fileUri = FileProvider.getUriForFile(activity, "com.szewec.ps.provider", new File(mFilePath));
        } else {
            //在版本低于此的时候，做一些处理
            fileUri = Uri.fromFile(new File(mFilePath));// create a file to save the video
        }

        LogUtil.i(TAG, "Build.MANUFACTURER：" + Build.MANUFACTURER);
        if (Build.MANUFACTURER.equalsIgnoreCase("vivo")) {
            //vivo手机特殊处理，vivo手机对路径要求不一样
        } else {
        }
        intentVIDEO.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);  // set the image file name
        //intentVIDEO.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); //设置录制时画面的质量(0或者1), 不设置默认是中等质量
        intentVIDEO.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 5 * 60); //限制录制时间为5分钟

        // start the Video Capture Intent
        activity.startActivityForResult(intentVIDEO, requestCodeVideo);

        return mFilePath;
    }

    /**
     * 调用系统相机拍照、录制所需权限！
     *
     * @param activity
     */
    public static void checkPermission(Activity activity) {
        //23以上调用系统相机拍照、录制所需权限！
        if (Build.VERSION.SDK_INT >= 23) {
            List<String> permissionStrs = new ArrayList<>();
            int hasWriteSdcardPermission =
                    ContextCompat.checkSelfPermission(
                            activity,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (hasWriteSdcardPermission !=
                    PackageManager.PERMISSION_GRANTED) {
                permissionStrs.add(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                );
            }

            int hasCameraPermission = ContextCompat.checkSelfPermission(
                    activity,
                    Manifest.permission.CAMERA);
            if (hasCameraPermission != PackageManager.PERMISSION_GRANTED) {
                permissionStrs.add(Manifest.permission.CAMERA);
            }
            String[] stringArray = permissionStrs.toArray(new String[0]);
            if (permissionStrs.size() > 0) {
                activity.requestPermissions(stringArray, 123);
                return;
            }
        }
    }

    /**
     * 获取文件时长
     *
     * @param mUri 文件路径
     * @return
     */
    public static long getDuration(String mUri) {
        MediaPlayer player = new MediaPlayer();
        try {
            player.setDataSource(mUri);  //音频文件的路径
            player.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
        int duration = player.getDuration();//获取音频的时间.
        player.release();//记得释放资源
        return duration;
    }

    /**
     * 获取文件名及后缀
     */
    public static String getSuffix(String path) {
        if (TextUtils.isEmpty(path)) {
            return "";
        }
        int start = path.lastIndexOf(".");
        if (start != -1) {
            return path.substring(start);
        } else {
            return "";
        }
    }

    /**
     * 删除附件列表里面的新增按钮
     * @param list
     */
    public static void removeFileIsAddInList(List<AlbumFile> list) {
        if (ListUtil.isNotEmpty(list)) {
            Iterator<AlbumFile> iterator = list.iterator();
            while (iterator.hasNext()) {
                AlbumFile albumFile = iterator.next();
                if (albumFile.isAdd() || albumFile.getType() == Constants.FileType.RECORD_SOUND) {
                    iterator.remove();
                }
            }
        }
    }

    /**
     * 删除Map中附件列表里面的新增按钮
     * @param listMap
     */
    public static void removeFileIsAddInMap(Map<String, List<AlbumFile>> listMap) {
        if (listMap != null && listMap.size() > 0) {
            for (List<AlbumFile> list : listMap.values()) {
                removeFileIsAddInList(list);
            }
        }
    }

    /**
     * 把AlbumFile对象转换成MediaFile对象
     *
     * @param list
     * @return
     */
    public static List<MediaFile> convert2MediaFile(List<AlbumFile> list) {
        List<MediaFile> retList = new ArrayList<>();
        if (list == null)
            return retList;
        for (AlbumFile albumFile : list) {
            MediaFile mediaFile = new MediaFile();
            //去掉压缩
            mediaFile.setPath(albumFile.getPath().split("\\?")[0]);
            mediaFile.setFileName(albumFile.getName());
            mediaFile.setDuration(albumFile.getDuration());
            mediaFile.setMime(albumFile.getMime());
            //如果是网络视频给一个大于1的时长,标记是视频
            if (albumFile.getPath().contains("http") && albumFile.getType() == Constants.FileType.VIDEO){
                mediaFile.setUrl(albumFile.getPath());
                mediaFile.setDuration(10);
            }
            retList.add(mediaFile);
        }
        return retList;
    }
}
